# __init__.py

from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from datetime import timedelta
import os

# 创建 SQLAlchemy 实例
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    CORS(app)  # 允许所有来源的跨域请求

    app.config['SECRET_KEY'] = os.urandom(24)
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)

    # 配置知识库数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///knowledge_base.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # 配置情感分析数据库
    app.config['SQLALCHEMY_BINDS'] = {
        'sentiment': 'sqlite:///sentiment_analysis.db'
    }

    db.init_app(app)

    with app.app_context():
        # 创建所有数据库表结构
        db.create_all()

    # 注册蓝图
    from .auth import auth_bp
    from .chatbot import chatbot_bp
    from .knowledge_base import knowledge_base_bp
    from .intent_recognition import intent_recognition_bp
    from .sentiment_analysis import sentiment_analysis_bp

    app.register_blueprint(auth_bp)
    app.register_blueprint(chatbot_bp)
    app.register_blueprint(knowledge_base_bp)
    app.register_blueprint(intent_recognition_bp)
    app.register_blueprint(sentiment_analysis_bp)

    return app
